package com.xiyu.service.repository.customer.pool;

import com.xiyu.service.model.customer.pool.*;
import com.xiyu.service.model.system.dept.SystemDeptFetcher;
import com.xiyu.service.model.system.dept.SystemPost;
import com.xiyu.service.model.system.dept.SystemPostFetcher;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.sql.JoinType;
import org.babyfish.jimmer.sql.ast.Predicate;

import java.util.Optional;
import java.util.List;

public interface CustomerPoolRuleRepository extends JRepository<CustomerPoolRule, Long> {
    CustomerPoolRuleTable customerPoolRuleTable = CustomerPoolRuleTable.$;

    default Optional<CustomerPoolRule> findDetailById(Long id){
        return sql().createQuery(customerPoolRuleTable)
                .where(customerPoolRuleTable.id().eq(id))
                .select(customerPoolRuleTable.fetch(CustomerPoolRuleFetcher.$.allTableFields()
                        .rulePosts(CustomerPoolRulePostFetcher.$.allTableFields())
                        .ruleDepts(CustomerPoolRuleDeptFetcher.$.allTableFields())
                ))
                .fetchOptional();
    }

    default List<CustomerPoolRule> findDetail(){
        return sql().createQuery(customerPoolRuleTable)
                .orderBy(customerPoolRuleTable.id().desc())
                .select(customerPoolRuleTable.fetch(CustomerPoolRuleFetcher.$.allTableFields()
                        .rulePosts(CustomerPoolRulePostFetcher.$.allTableFields().post(SystemPostFetcher.$.name()))
                        .ruleDepts(CustomerPoolRuleDeptFetcher.$.allTableFields().dept(SystemDeptFetcher.$.name()))
                ))
                .execute();
    }

    default List<CustomerPoolRule> findMatchRule(Long deptId, List<Long> postId){
        return sql().createQuery(customerPoolRuleTable)
                .where(customerPoolRuleTable.isEnable().eq(true))
                .where(
                        Predicate.or(
                                customerPoolRuleTable.asTableEx().ruleDepts(JoinType.LEFT).deptId().eq(deptId),
                                customerPoolRuleTable.asTableEx().ruleDepts(JoinType.LEFT).id().isNull()
                        )
                )
                .where(
                        Predicate.or(
                                customerPoolRuleTable.asTableEx().rulePosts(JoinType.LEFT).postId().in(postId),
                                customerPoolRuleTable.asTableEx().rulePosts(JoinType.LEFT).id().isNull()
                        )
                )
                .select(customerPoolRuleTable)
                .distinct().execute();
    }

    Optional<CustomerPoolRule> findByName(String name);


}